package com.TheyChat.service.config.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.TheyChat.service.config.auth.entity.UserAuthInfo;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
/**
 * @author quxiang
 * @date 2021/12/30 13:53
 */
@Component
public class TokenUtil {
    private static final int EXPIRE_TIME= 60*24*60;//token到期时间1h
    private static final String TOKEN_SECRET= "6ae6acab8f6711eeb9d6d49390175afb";
    //密钥盐，跟AuthUtils里面的密钥一模一样，否则无法验签

    /**
     * 创建一个token
     * @param user
     * @return
     */
    public static String sign(UserAuthInfo user){
        String token=null;
        try {
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.MINUTE, EXPIRE_TIME);
            Date expireAt = nowTime.getTime();
            token = JWT.create()
                    .withIssuer("auth0")//发行人
                    .withClaim("id",user.getId())   //存放数据
                    .withClaim("username",user.getUsername())   //存放数据
                    .withClaim("password",user.getUserPwd())
                    .withClaim("orgId",user.getOrgId())
                    .withClaim("userType",user.getUserType().getValue())
                    .withClaim("orgCode",user.getUserType().getValue())
                    .withClaim("roleId",user.getRoleId())
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException|JWTCreationException je) {

        }
        return token;
    }

//    public static String sign(UserAuthInfo user){
//        String token=null;
//        try {
//            Calendar nowTime = Calendar.getInstance();
//            nowTime.add(Calendar.MINUTE, EXPIRE_TIME);
//            Date expireAt = nowTime.getTime();
//            token = JWT.create()
//                    .withIssuer("auth0")//发行人
//                    .withClaim("id",user.getId())   //存放数据
//                    .withClaim("username",user.getUsername())   //存放数据
//                    .withClaim("password",user.getPassword())
//                    .withClaim("orgId",user.getOrgId())
//                    .withClaim("userType",user.getUserType().getValue())
//                    .withClaim("roleId",user.getRoleId())
//                    .withExpiresAt(expireAt)//过期时间
//                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
//        } catch (IllegalArgumentException|JWTCreationException je) {
//
//        }
//        return token;
//    }
    /**
     * 对token进行验证
     * @param token
     * @return
     */
    public static Boolean verify(String token){
        try {
            JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
            DecodedJWT decodedJWT=jwtVerifier.verify(token);
            System.out.println("username: " + TokenUtil.getUsername(token));
            System.out.println("过期时间：    " + decodedJWT.getExpiresAt());
        } catch (IllegalArgumentException |JWTVerificationException e) {
            //抛出错误即为验证不通过
            return false;
        }
        return true;
    }

    /**
     * 获取用户名
     */
    public static String getUsername(String token)
    {
        try{
            DecodedJWT jwt=JWT.decode(token);
            return  jwt.getClaim("username").asString();
        }catch (JWTDecodeException e)
        {
            return null;
        }


    }
}

